#! /usr/bin/env python
# -*- coding: utf-8 -*-

# *************************************************************
#     Filename @  core.py
#       Author @  Huoty
#  Create date @  2016-07-30 23:28:12
#  Description @  core
# *************************************************************

from __future__ import absolute_import, print_function

import sys
import datetime

from prettytable import PrettyTable

from .utils import str_to_date, convert_int, Colorizing
from .train import TrainTicketsQuery, get_train_timetable
from .station import get_station_open_time


if sys.version_info[0] < 3:
    import sys
    reload(sys)
    sys.setdefaultencoding('utf-8')


_c = Colorizing()


def query_remaining_tickets(from_station, to_station, date, train_types=None, seat_types=None):
    """火车余票查询"""
    ttq = TrainTicketsQuery(from_station, to_station, date, train_types, seat_types)
    trains = ttq.query()
    if not trains:
        print(_c("没有找到该行程的车次信息！", "red"))
        return

    seats = {
        "gr": "高级软卧",
        "rw": "软卧",
        "rz": "软座",
        "tz": "特等座",
        "wz": "无座",
        "yw": "硬卧",
        "yz": "硬座",
        "ze": "二等座",
        "zy": "一等座",
        "sw": "商务座",
    }

    pt = PrettyTable()
    seat_types = seat_types if seat_types else ["sw", "tz", "zy", "ze", "gr", "rw", "yw", "rz", "yz", "wz"]
    pt.field_names = ["车次", "车站", "时间", "历时"] + [seats[seat] for seat in seat_types]
    for train in trains:
        day_diff = {
            "0": "当日到达",
            "1": "次日到达",
            "2": "第二日到达",
            "3": "第三日到达",
            "4": "第四日到达",
        }.get(train[6])

        pt.add_row([
            train[0],
            _c(train[1], "green") + '\n' + _c(train[2], "red"),
            _c(train[3], "green") + "\n" + _c(train[4], "red"),
            "{}小时{}分钟".format(*[int(x) for x in train[5].split(':')]) + '\n' + _c(day_diff, "red")] +
            [_c(s, "bold") if 0 < convert_int(s) < 10 else s for s in train[7:]
        ])

    print(pt)

def watch_remaining_tickets(trains, date, seat_types=None, frequency=None, to_mails=None):
    """监控余票"""
    pass

def query_station_open_time(station):
    """查询站点开放售票时间"""
    pt = PrettyTable()
    pt.field_names = ["车站", "开放售票时间"]
    pt.add_row([station, get_station_open_time(station)])
    print(pt)

def query_train_timetable(train_no):
    """查询车次的时刻表"""
    pt = PrettyTable()
    pt.field_names = ["站次", "车站", "到达时间", "发车时间", "停留时间"]
    time_table = get_train_timetable(train_no)
    if not time_table:
        print(_c("没有找到车次 %s 的时刻表信息" % train_no, "red"))
    for row in time_table:
        pt.add_row(row)
    print(pt)
